﻿using System;
using WD.Db.Contract;
using WD.Db.Contract.Model;
using WD.Core.Cache;
using WD.Framework.Contract;

namespace WD.Web
{
    public class UserContext
    {
        protected IAuthCookie authCookie;
        protected 账户凭证类型 accountType = 账户凭证类型.其它;
        public UserContext(IAuthCookie authCookie, 账户凭证类型 accountType)
        {
            this.authCookie = authCookie;
            this.accountType = accountType;
        }

        public Rbac_LoginInfo LoginInfo
        {
            get
            {
                return CacheHelper.GetItem("Rbac_LoginInfo", () =>
                {
                    if (authCookie.UserToken == Guid.Empty)
                        return null;
                    accountType = (账户凭证类型)authCookie.Type;

                    var loginInfo = new Rbac_LoginInfo();
                    switch (accountType)
                    {
                        case 账户凭证类型.商家:
                            loginInfo = ServiceContext.Current.Shop_LoginInfoService.GetLoginInfo(authCookie.UserToken);
                            break;
                        case 账户凭证类型.管理员:
                            loginInfo = ServiceContext.Current.Rbac_LoginInfoService.GetLoginInfo(authCookie.UserToken);
                            break;
                        default:
                            //loginInfo = ServiceContext.Current.Rbac_LoginInfoService.GetLoginInfo(authCookie.UserToken);
                            break;
                    }
                    // var loginInfo = ServiceContext.Current.Rbac_LoginInfoService.GetLoginInfo(authCookie.UserToken);

                    if (loginInfo != null && loginInfo.UserID > 0 && loginInfo.UserID != this.authCookie.UserId)
                        throw new Exception("非法操作，试图通过网站修改Cookie取得用户信息！");

                    return loginInfo;
                });
            }
        }
    }
}
